//拦截器
import axios from 'axios'
import { Dialog } from 'vant'
import { Loading } from "element-ui";
import VUE_APP_BASE_API from '@/api/http.js'
import VUE_APP_BASE_API_5G from '@/api/http5g.js'
import { cosh } from 'core-js/fn/number';
let loading
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(255, 255, 255, 0.9)'
    })
}
function endLoading() {
    loading.close()
}
const STATUS_CODE_MAP = new Map([
    [400,'错误请求'],
    [401,'未授权 请重新登录'],
    [403,'拒绝访问'],
    [404,'请求错误，没找到资源'],
    [405,'请求方法未允许'],
    [408,'请求超时'],
    [500,'服务器端出错'],
    [501,'网络未实现'],
    [502,'网络错误'],
    [503,'错误请求'],
    [504,'网络超时'],
    [505,'http版本不支持请求']
])


class HttxError extends Error {
    constructor(message) {
        super(message);
        this.name = this.constructor.name;
    }
}
class HttxStatusError extends HttxError {
    constructor(message, statusCode, dataResult) {
        super(message);
        this.name = this.constructor.name;
        this.statusCode = statusCode;
        this.dataResult = dataResult;
    }
}


//创建实例
const service = axios.create({
    timeout:30*1000
})

//请求拦截器
service.interceptors.request.use(config=>{
    if(config.url.indexOf('api/pay/check')>0){
        console.log("api/pay/check")
    }else{
        startLoading()
    }
    config.headers = config.headers || {
        'content-type': 'application/x-www-form-urlencoded',
    }
    let token = weixin.getToken();
    //单用户手机号转换成多用户的token
    var token5g = localStorage.getItem("token5g");
    if(!token5g){
        let url = VUE_APP_BASE_API_5G.VUE_APP_BASE_API_5G+'api/user/mobilelogin'
        let param = {
            mobile:weixin.loginMobile()//登录手机号
        }
        axios.post(url,param)
            .then(function(res) {
                token5g=res.data.data.userinfo.token;
                console.log("=====11",res.data,token5g);
                localStorage.setItem("token5g",token5g)
                config.headers['token5g'] = '' + token5g
            })
            .catch(function(err) {
            });
    }
    if(token){
        config.headers['Authorization'] = '' + token;
        config.headers['token'] = '' + token;
        config.headers['token5g'] = '' + token5g;
        config.headers['domain'] = '' +VUE_APP_BASE_API.VUE_APP_BASE_API
    }
    return config
},error=>{
    Promise.reject(error)
})

//响应拦截
service.interceptors.response.use(response => {
    endLoading()
    return response
}, error => {
    endLoading()
    console.log("error.response",error)
    let statusCode = error.response.status;
    let dataResult = error.response.data;

    try {
        if (statusCode >= 500) {// 5xx

            throw new HttxStatusError('系统错误', statusCode, dataResult);
        } else if (statusCode >= 400) {// 4xx
            throw new HttxStatusError('请求出错', statusCode, dataResult);
        }
        throw new Error(`Unsupported statusCode ${statusCode}`);
    } catch (error2) {
        //return error2
        handleError(error2);
    }
})


function handleError(error) {
    if (error instanceof HttxStatusError) {
        let statusCode = error.statusCode;
        let dataResult = error.dataResult;
        if (statusCode == 401) {
            weixin.login(); //请先登录
        } else {
            let msg;
            if (Object.prototype.toString.call(dataResult) === '[object Object]') {
                msg = dataResult.msg;
            }
            msg = msg || STATUS_CODE_MAP.get(statusCode) || error.message;
            Dialog({message:msg})
            console.log(msg);
        }
    } else if (error instanceof Error) {
        Dialog({message:error.message})
        console.log(error.message);
    } else {
        Dialog({message:error})
        console.log(error);
    }

    throw error;
}


export default service
